"""
# @Author: lichuang
# @Create: 2024/09/30
# @Last Modified: 2024/09/30
# @Last Editor:
# @Filename: exception_handlers.py
# @Description:
"""

from django.http import Http404

from rest_framework import exceptions
from rest_framework.response import Response
from rest_framework.exceptions import ValidationError
from rest_framework.exceptions import Throttled
from rest_framework.exceptions import PermissionDenied
from rest_framework.exceptions import NotAuthenticated
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.views import set_rollback


def extract_error_messages(detail):
    """递归提取错误消息并返回连接成的字符串，并删除多余空格"""
    if isinstance(detail, list):
        messages = ' '.join(extract_error_messages(item) for item in detail)
    elif isinstance(detail, dict):
        messages = ' '.join(extract_error_messages(value) for value in detail.values())
    elif isinstance(detail, str):
        messages = detail
    elif hasattr(detail, 'string'):  # 处理 ErrorDetail 对象
        messages = detail.string
    else:
        messages = str(detail)

    # 去掉多余空格
    return messages.replace(" ","")

def exception_handler(exc, context):
    if hasattr(exc, "detail"):
        print(exc.detail)
    if isinstance(exc, Http404):
        exc = exceptions.NotFound()
        exc.ret_code = 1001
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.PermissionDenied()
        exc.ret_code = 1002
    elif isinstance(exc, (AuthenticationFailed, NotAuthenticated)):
        exc.ret_code = 1003
    elif isinstance(exc, Throttled):
        exc.ret_code = 1004
    elif isinstance(exc, ValidationError):
        exc.ret_code = 1005
        if isinstance(exc.detail, list):
            err_msg = exc.detail[0]
        elif isinstance(exc.detail, dict):
            err_msg = extract_error_messages(exc.detail)
        else:
            err_msg = ""
        return Response({'code': exc.ret_code, 'msg': err_msg})
    elif isinstance(exc, ValueError):  # 添加对 ValueError 的处理
        err_msg = str(exc)
        return Response({'code': 1006, 'msg': err_msg})
    # 只处理drf相关的异常
    if isinstance(exc, exceptions.APIException):
        headers = {}
        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['Retry-After'] = '%d' % exc.wait

        # if isinstance(exc.detail, (list, dict)):
        #     data = exc.detail
        if isinstance(exc.detail, dict) and "code" in exc.detail:
            data = exc.detail
        else:
            code = getattr(exc, 'ret_code', None) or -1
            data = {'code': code, 'msg': exc.detail}

        set_rollback()
        # return Response(data, status=exc.status_code, headers=headers)
        return Response(data)
    return None
